package org.imlinker.buddy;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.util.HashMap;
import java.util.Map;

import org.imlinker.gui.ChatWindow;
import org.imlinker.message.MessageList;
import org.imlinker.util.StringUtils;

import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;

public class ChatProxy {

	public ChatProxy(final XMPPConnection connection,
			final MessageList messageList, final ChatAdapter adapter) {

		this.connection = connection;
		this.messageList = messageList;
		this.adapter = adapter;

		java.util.ResourceBundle bundle = java.util.ResourceBundle
				.getBundle("org/imlinker/gui/Bundle");
		linkToLabel = bundle.getString("ChatProxy.linkto");
	}

	/**
	 * 在窗口不可见的情况下（包括窗口还没有生成，窗口已经生成但不可见），返回true，以帮助加入消息.
	 */
	public boolean createChatWindow(final String name, final boolean b,
			final String m) {
		// 检测聊天窗口是否已经存在
		ChatWindow chatWindow = map.get(name);

		RosterEntry entry = connection.getRoster().getEntry(name);
		String nickName = entry.getName();

		if (StringUtils.isEmpty(nickName)) {
			nickName = "";
		}
		nickName = nickName + "(" + name + ")";
		final String titleName = nickName;

		if (chatWindow != null) {
			if (b) {
				chatWindow.setVisible(true);
				chatWindow.setState(Frame.NORMAL);
				return false;
			}

			if (!chatWindow.isVisible()) {
				return true;
			}

			return false;
		}

		// 如果不存在的话新建一个
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				final ChatWindow chatWindow = new ChatWindow(adapter,
						titleName, m, linkToLabel);
				chatWindow.addWindowListener(new WindowAdapter() {
					String chatString = "chat:" + name;

					@Override
					public void windowActivated(final WindowEvent e) {
						messageList.setBlackName(chatString);

						chatWindow.active();
					}

					public void windowDeactivated(final WindowEvent e) {
						messageList.removeBlackName(chatString);
					}
				});

				map.put(name, chatWindow);
				chatWindow.setVisible(b);
			}
		});

		return true;
	}

	private Map<String, ChatWindow> map = new HashMap<String, ChatWindow>();

	private MessageList messageList;

	private XMPPConnection connection;

	private String linkToLabel;

	private ChatAdapter adapter;

}
